package com.xiemingtian.navdemo;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.util.LongSparseArray;

import java.io.IOException;
import java.util.Enumeration;

import dalvik.system.DexFile;

public class Loader {
    public final static LongSparseArray<Entry> destinations = new LongSparseArray<>();
    static void load(Context context) throws IOException, IllegalAccessException, InstantiationException {
        DexFile dex = new DexFile(context.getPackageResourcePath());
        Enumeration<String> entries = dex.entries();

        while (entries.hasMoreElements()) {
            String entryName = entries.nextElement();
            if (entryName.startsWith("com.xiemingtian.navdemo")){
                try {
                    Class<?> aClass = Class.forName(entryName);
                    Nav annotation = aClass.getAnnotation(Nav.class);
                    if (annotation != null){
                        Object o = aClass.newInstance();
                        if (o instanceof Fragment){
                            Entry entry = new Entry();
                            entry.actions = annotation.actions();
                            entry.dest = annotation.dest();
                            entry.isStart = annotation.isStart();
                            entry.aClass = (Class<? extends Fragment>) aClass;
                            destinations.append(annotation.id(), entry);
                        }
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static class Entry{
        public Class<? extends Fragment> aClass;
        public int[] actions;
        public int[] dest;
        public boolean isStart;
    }

}
